package com.example.webdownloadserver.job;

import com.example.webdownloadserver.base.TaskUploadThreadPool;
import com.example.webdownloadserver.service.TaskCenterService;
import com.example.webdownloadserver.vo.TaskCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class UploadJob{
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private TaskCenterService taskCenterService;

	@Scheduled(cron = "0 0/2 * * * ?")
	public void execute() {
		logger.info("开始处理上载任务...");
		Long taskId = 0L;
		try {
			// 当前活跃线程数
			int activeNum = TaskUploadThreadPool.getActiveCount();
			// 根据线程池执行能力获取抓取任务数
			int idle = TaskUploadThreadPool.getIdleNum();
			logger.info("当前上传线程池空余线程数：{}", idle);
			if (0 >= idle) {
				logger.info("当前上传线程池有{}任务在执行，已经没有空余线程，等待下次轮询", activeNum);
				return;
			}
			List<TaskCenter> list = taskCenterService.uploadTaskCenterList(idle);
			if (null != list && list.size() > 0) {
				logger.info("需处理的上传记录共【{}】条", list.size());
				for (TaskCenter task : list) {
					taskId = task.getTaskId();
					TaskUploadThreadPool.upload(taskCenterService, task);
				}
			} else {
				logger.info("需处理的上传记录共【0】条");
			}
		} catch (Exception e) {
			logger.error("处理上传记录出错---任务ID[{}]", taskId, e);
		} catch (Throwable e) {
			logger.error("处理上传记录出错---任务ID[{}]", taskId, e);
		}

	}

}
